<?php

namespace App\Repository\Orders;

use App\Models\Orders\OrdersLabelModel as Model;
use App\Repository\BaseRepository;

class OrdersLabelRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new Model();
//    $this->log = new Logger('anchor');
//    $this->log->pushHandler(
//      (new RotatingFileHandler(storage_path('/logs/anchor.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//    );
        parent::__construct();
    }

    public function index($params, $page = 1, $limit = 10)
    {
        $pk = $this->model->getKeyName();
//        先要总数
        $totalRows = 0;
        if ($page <= 1) {
            $totalRows = $this->model->count($pk);
        }
//        再加上分页查询
        $rows = $this->model->page($page, $limit)->get();
        return $this->returnMsg(200, '查询成功', $rows, $totalRows);
    }

//列表
    public function dataList()
    {
        return $this->model->select(['id', 'name'])->orderByDesc('id')->get();
    }

    //删除
    public function del($id)
    {
        $where = ["id" => $id];
        $result = $this->model->where($where)->count();
        if ($result) {
            $del = $this->model->where($where)->delete();
            return $this->returnMsg(200, "删除成功");
        }
        return $this->returnMsg(1, "数据不存在");
    }

    public function edit($params)
    {
        if (!$params['id']) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $mustField = [
            'name'
        ];
        $msgField = [
            'name' => '类型名字不能为空'
        ];
        $updateData = $this->getRealData($params, $mustField, [], $msgField);
        if (!empty($updateData) && is_string($updateData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $updateData
            );
        }
        $where = ['id' => $params['id']];
        $haveData = $this->model->where($where)->count("id");
        if (!$haveData) {
            return $this->returnMsg(100, '未查询到修改的数据');
        }
        $res = $this->model->where($where)->update($updateData);
        if (false !== $res) {
            return $this->returnMsg(200, '修改成功!');
        }
        return $this->returnMsg(3, '请重新修改');
    }

//保存
    public function add($params)
    {
        $name = $params['name'];
        $usersId = $params['user']['id'];
        $id = $this->model->insertGetId(['name' => $name, 'users_id' => $usersId]);
        if ($id > 0) {
            return $this->returnMsg(200, '操作成功', ['id' => $id, 'name' => $name]);
        }
        return $this->returnMsg(100, '操作失败');
    }

}
